__author__ = 'Administrator'
import re,os,sys,time
sys.path.append('/root/tornado-yw/mod/')
import sql
def mysqls():
    return  sql.Mysql('127.0.0.1','root','123456','kkk')


ipa = {}
err_nb = {'200':0,'304':0,'404':0}
number={'total':0}
IES = {'MSIE':0,'Firefox':0,'Chrome':0}
pon={'"GET':0,'"POST':0}
#IES['AB'] = ['MSIE', 'Firefox', 'Chrome']
Logfile = '/var/log/nginx/access.log'
try:
    f = open(Logfile, 'r').readlines()
except:
    print(Logfile,'文件不存在或打开出错！')
    os.system('pause')
    sys.exit(1)
for i in f:
    ip=i.split()
    #print(ip[-8])
    for n in list(IES):
        number['total']+=1
        if re.search(n, i):
             if IES.get(n) == None:
                 IES.setdefault(n,1)
             else:
                 IES[n]+=1

    if ipa.get(ip[0]) == None:
        ipa.setdefault(ip[0], 1)
    else:
        ipa[ip[0]]+=1

    if err_nb.get(ip[8]) == None:
        err_nb.setdefault(ip[8], 1)
    else:
        err_nb[ip[8]] += 1

    if pon.get(ip[5]) == None:
        pon.setdefault(ip[5], 1)
    else:
        pon[ip[5]] += 1


data_list = {}
print('IP访问次数：')
sorted(ipa.items())
for i in ipa:
    pass
    #print(i, '----->', ipa.get(i))
    #print('%-15s %-8s %s' % (i, '----->', ipa.get(i)))

print('HTTP状态码数目：')
sorted(err_nb.items(), reverse=False)
for i in err_nb:
    #print('%-5s %-8s %s' % (i, '----->', err_nb.get(i)))
    data_list[i]=err_nb.get(i)

print('浏览器访问的数目：', IES.get('AB'))
sorted(IES.items(), reverse=True)
for i in IES:
    if i == 'AB':
        continue
    #print('%-8s %-8s %s' % (i, '----->', IES.get(i)))
    data_list[i]=IES.get(i)
#os.system('pause')

sorted(pon.items(), reverse=False)
for i in pon:
    #print('%-5s %-8s %s' % (i, '----->', pon.get(i)))
    data_list[i]=pon.get(i)
data_list['number']=number['total']
#print(data_list)
class test:
    def __init__(self):
        #print('9999999999999')
        self.tm=int(time.time())
        self.post=data_list['"POST']
        self.get=data_list['"GET']
        self.st200=data_list['200']
        self.st304=data_list['304']
        self.st404=data_list['404']
        self.ie=data_list['MSIE']
        self.firefox=data_list['Firefox']
        self.chrom=data_list['Chrome']
        self.number=data_list['number']


    def run(self):
        mysql = mysqls()
        sql='''
        INSERT INTO `nginx_access` (`time`,`post`,`get`,`200`,`304`,`404`,`ie`,`firefox`,`chrom`,`number`) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');
        '''
        mysql.cmd(sql%(self.tm,self.post,self.get,self.st200,self.st304,self.st404,self.ie,self.firefox,self.chrom,self.number))
        mysql.commit()
        mysql.close()
        #print(data_list)

test().run()
